import * as echarts from "echarts";
import styles from "../index.module.less";
import { queryParams } from "./store";
import { Dayjs } from "dayjs";
// 给定两个时间计算天数差
export function GetDaysDiff(startDateString, endDateString) {
  const start: any = new Date(startDateString);
  const end: any = new Date(endDateString);
  const timeDiffInMs = Math.abs(end - start);
  const daysDiff = Math.ceil(timeDiffInMs / (1000 * 3600 * 24));
  return daysDiff;
}
// 给定两个时间计算月差
export function GetMonthDiff(startDateString, endDateString) {
  const start = new Date(startDateString);
  const end = new Date(endDateString);
  const monthDiff =
    (end.getFullYear() - start.getFullYear()) * 12 +
    (end.getMonth() - start.getMonth());
  return Math.abs(monthDiff);
}

// 本月一号
export function GetThisMonthFirstDay() {
  const date = new Date();
  date.setDate(1);
  const cTime = new Date(new Date(date).toLocaleDateString()).getTime();
  const $date = new Date(cTime);
  const year = $date.getFullYear();
  let month: any = $date.getMonth() + 1;
  let day: any = $date.getDate();
  month = month < 10 ? "0" + month : month;
  day = day < 10 ? "0" + day : day;
  return year + "-" + month + "-" + day;
}
// 上个月的今天
export const GetLastMonthToday = () => {
  const today = new Date();
  today.setMonth(today.getMonth() - 1);
  const oneMonthAgo = today.toDateString();
  return $dayjs(new Date(oneMonthAgo)).format("YYYY-MM-DD");
};
// 11个月以前的当前日期时间
export const Get11MonthAgo = () => {
  const today = new Date();
  today.setMonth(today.getMonth() - 11);
  return today.toLocaleString();
};
// 29天前
export const Get29DayAgo = () => {
  const today = new Date();
  today.setHours(0);
  today.setMinutes(0);
  today.setSeconds(0);
  today.setMilliseconds(0);
  today.setDate(today.getDate() - 29);
  return today.toLocaleString();
};
// 三个月前的今天
export const GetThreeMonthsAgoToday = () => {
  let today = new Date();
  today.setMonth(today.getMonth() - 3);
  let threeMonthsAgo = today.toISOString().split("T")[0];
  return threeMonthsAgo;
};
// 一年前的今天
export const GetOneYearAgoToday = () => {
  let today = new Date();
  today.setUTCFullYear(today.getUTCFullYear() - 1);
  let oneYearAgo =
    today.getUTCFullYear() +
    "-" +
    (today.getUTCMonth() + 1) +
    "-" +
    today.getUTCDate();
  return oneYearAgo;
};
// 给两个日期获取连续的日
export function GetContinuousDate(startTime, endTime) {
  startTime = new Date(startTime);
  endTime = new Date(endTime);
  const dateArray: any[] = [];
  startTime.setHours(0);
  endTime.setHours(23, 59, 59);
  while (startTime <= endTime) {
    dateArray.push($dayjs(new Date(startTime)).format("YYYY/MM/DD"));
    startTime.setDate(startTime.getDate() + 1);
  }
  return dateArray;
}
// 给两个日期获取连续的月
export function GetContinuousMonths(startDateStr, endDateStr) {
  let start = new Date(startDateStr);
  let end = new Date(endDateStr);
  if (isNaN(start.getTime()) || isNaN(end.getTime())) {
    return $t("overview46");
  }
  let months: any = [];
  while (start <= end) {
    months.push(`${start.getFullYear()}/${start.getMonth() + 1}`);
    start.setMonth(start.getMonth() + 1);
  }
  return months;
}
const startTime = $dayjs(getTimeByZone(new Date(Get11MonthAgo())));
const endTime = $dayjs(getTimeByZone(new Date()));
const range_date = ref<any>(
  GetContinuousMonths(startTime.format("YYYY/MM"), endTime.format("YYYY/MM"))
);
const format = ref("YYYY/MM");
const mwd = ref<any>($t("dict44"));
const picker = ref("month");
const default_month_formatter = function (value) {
  const date = new Date(value);
  return [date.getFullYear(), date.getMonth() + 1]
    .map((item) => String(item).padStart(2, "0"))
    .join("/");
};
const default_day_formatter = function (value) {
  const date = new Date(value);
  return [date.getFullYear(), date.getMonth() + 1, date.getDate()]
    .map((item) => String(item).padStart(2, "0"))
    .join("/");
};
let formatter = default_month_formatter;
export default defineComponent({
  setup(props, { expose }) {
    const _self = reactive<any>(getCurrentInstance());
    const searchParams = reactive<any>({
      mwd: "month",
      rangeDate: [
        $dayjs(getTimeByZone(new Date(Get11MonthAgo()))),
        $dayjs(getTimeByZone(new Date())),
      ],
    });
    const visitor_number = ref<any>([]);
    const active_user = ref<any>([]);
    const timeMap = reactive([
      {
        label: $t("dict44"),
        value: "month",
      },
      {
        label: $t("dict45"),
        value: "day",
      },
      // {
      //   label: $t("dict46"),
      //   value: "week",
      // },
      // {
      //   label: $t("dict47"),
      //   value: "year",
      // },
    ]);
    const formInline = reactive({});
    const drawEchart = () => {
      const maxyAxisValue = Math.max(
        ...[...visitor_number.value, ...active_user.value]
      );
      const minyAxisValue = Math.min(
        ...[...visitor_number.value, ...active_user.value]
      );
      let option = {
        tooltip: {
          trigger: "axis",
        },
        legend: {
          data: [$t("overview47"), `${mwd.value}${$t("overview31")}`],
          bottom: 0,
        },
        grid: {
          top: "3%",
          left: 16,
          right: 30,
          bottom: "10%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: range_date.value,
          axisLabel: {
            interval: 0,
            rotate: 45,
            formatter,
          },
        },
        yAxis: {
          type: "value",
          max: maxyAxisValue,
          min: minyAxisValue,
          interval: Math.ceil((maxyAxisValue - minyAxisValue) / 5),
          axisLabel: {
            formatter: (value) => value,
          },
        },
        series: [
          {
            name: $t("overview47"),
            type: "line",
            data: visitor_number.value,
          },
          {
            name: `${mwd.value}${$t("overview31")}`,
            type: "line",
            data: active_user.value,
          },
        ],
      };
      const el: any = _self.refs["chart_box"];
      const _this: any = echarts.init(el);
      _this.setOption(option);
      window.addEventListener("resize", () => _this.resize());
    };
    const fetchData = async () => {
      let start_date = null;
      let end_date = null;
      if (searchParams.mwd === "month") {
        start_date = searchParams.rangeDate[0]
          .startOf("month")
          .format("YYYY-MM-DD");
        end_date = searchParams.rangeDate[1]
          .endOf("month")
          .format("YYYY-MM-DD");
      }
      if (searchParams.mwd === "day") {
        start_date = searchParams.rangeDate[0].format("YYYY-MM-DD");
        end_date = searchParams.rangeDate[1].format("YYYY-MM-DD");
      }
      const res: any = await overviewApi.queryActiveUser({
        merchant_user_id:
          queryParams.merchant_user_id === ""
            ? undefined
            : queryParams.merchant_user_id,
        start_date,
        end_date,
        mwd: searchParams.mwd,
      });
      if (res.code != 200) return message.error(res.message);
      visitor_number.value = range_date.value.map((dateString) => {
        const dateArray = dateString.split("/");
        for (const item of res.data.list) {
          const cond =
            +dateArray[0] === +item.year && +dateArray[1] === +item.month;
          if (searchParams.mwd === "month") {
            if (cond) return +item.launch_user_num;
          }
          if (searchParams.mwd === "day") {
            if (cond && +dateArray[2] === +item.day)
              return +item.launch_user_num;
          }
        }
        return "";
      });
      active_user.value = range_date.value.map((dateString) => {
        const dateArray = dateString.split("/");
        for (const item of res.data.list) {
          const cond =
            +dateArray[0] === +item.year && +dateArray[1] === +item.month;
          if (searchParams.mwd === "month") {
            if (cond) return +item.login_user_num;
          }
          if (searchParams.mwd === "day") {
            if (cond && +dateArray[2] === +item.day)
              return +item.login_user_num;
          }
        }
        return "";
      });
      initObjAttr(formInline, res.data, "target");
    };
    const initPage = async () => {
      await fetchData();
      drawEchart();
    };
    expose({ initPage });
    watch(
      () => queryParams.merchant_user_id,
      () => initPage()
    );

    return () => (
      <div class={styles.line_chart_wrap}>
        <div class={styles.search} style="margin-left: 16px;">
          <div class={styles.flex_item}>
            <div>
              <a-range-picker
                v-model:value={searchParams.rangeDate}
                allowClear={false}
                format={format.value}
                onChange={(date: Dayjs, dateString: string) => {
                  const startDateString = dateString[0];
                  const endDateString = dateString[1];
                  if (searchParams.mwd === "month") {
                    range_date.value = GetContinuousMonths(
                      startDateString,
                      endDateString
                    );
                    const result = GetMonthDiff(startDateString, endDateString);
                    if (result >= 13) {
                      searchParams.rangeDate = [];
                      return message.warn(
                        `${$t("overview64")}12${$t("overview65")}`
                      );
                    }
                  }
                  if (searchParams.mwd === "day") {
                    range_date.value = GetContinuousDate(
                      startDateString,
                      endDateString
                    );
                    const result = GetDaysDiff(startDateString, endDateString);
                    if (result >= 31) {
                      searchParams.rangeDate = [];
                      return message.warn(
                        `${$t("overview64")}30${$t("overview66")}`
                      );
                    }
                  }
                  initPage();
                }}
                picker={picker.value}
              />
            </div>
          </div>

          <div class={styles.flex_item}>
            <div>
              <a-select
                v-model:value={searchParams.mwd}
                style="width: 70px"
                placeholder={$t("placeholder156")}
                options={timeMap}
                onChange={(value) => {
                  if (value === "month") {
                    format.value = "YYYY/MM";
                    picker.value = "month";
                    formatter = default_month_formatter;
                    mwd.value = $t("dict44");
                    range_date.value = GetContinuousMonths(
                      $dayjs(getTimeByZone(new Date(Get11MonthAgo()))).format(
                        "YYYY/MM"
                      ),
                      $dayjs(getTimeByZone(new Date())).format("YYYY/MM")
                    );
                  }
                  if (value === "day") {
                    format.value = "YYYY/MM/DD";
                    picker.value = "date";
                    formatter = default_day_formatter;
                    mwd.value = $t("dict45");
                    range_date.value = GetContinuousDate(
                      $dayjs(Get29DayAgo()).format("YYYY/MM/DD"),
                      $dayjs().format("YYYY/MM/DD")
                    );
                  }
                  // if (value === "year") {
                  //   const startTime = $dayjs(
                  //     getTimeByZone(new Date(GetOneYearAgoToday()))
                  //   );
                  //   const endTime = $dayjs(getTimeByZone(new Date()));
                  //   range_date.value = [
                  //     startTime.format("YYYY"),
                  //     endTime.format("YYYY"),
                  //   ];
                  // }
                  // if (value === "week") {
                  //   range_date.value = getLastWeek(6);
                  // }
                  searchParams.rangeDate = [
                    $dayjs(range_date.value[0]),
                    $dayjs(range_date.value[range_date.value.length - 1]),
                  ];
                  initPage();
                }}
              ></a-select>
            </div>
          </div>
        </div>
        <div class={styles.active_custom_chart} ref="chart_box"></div>
      </div>
    );
  },
});
